import re
import os
import json
import time
import random
import openpyxl
import requests
import argparse
from lxml import etree
from hashlib import md5
from openpyxl.styles import Font, Border, Side, Alignment
from bs4 import BeautifulSoup

def trans_by_ciba(word):
    # proxy = {'http': '127.0.0.1:1080', 'https': '127.0.0.1:1080'}
    url = f"https://www.iciba.com/word?w={word.replace(' ', '+')}"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
    try:
        # response = requests.get(url, headers=headers, proxies=proxy)
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')

        # 提取音标
        phonetic_elements = soup.find_all('ul', class_='Mean_symbols__fpCmS')
        phonetics = ""
        for element in phonetic_elements:
            # phonetics += element.get_text().strip()
            temp = element.find('li').get_text().strip()
            start_index = temp.find('[')
            end_index = temp.find(']')
            if start_index != -1 and end_index != -1:
                temp2 = temp[start_index:end_index + 1]
                phonetics += temp2
            break

        # 提取释义
        meaning_elements = soup.find_all('ul', class_='Mean_part__UI9M6')
        meanings = ""
        for element in meaning_elements:
            meanings += element.get_text().strip()

        return {
            'word': word,
            'proc': phonetics,
            'mean': meanings
        }
    except requests.RequestException as e:
        return f"请求出错: {e}"
        
    except Exception as e:
        return f"未知错误: {e}"

parser = argparse.ArgumentParser(description='读取文件名')
parser.add_argument('--file', type=str, help='要处理的文件名')
parser.add_argument('--word', type=str, help='要查找的单词')
args = parser.parse_args()
filename = ""
if args.file:
    filename = args.file
else:
    filename = '初一英语单词.xlsx'

if args.word:
    print(trans_by_ciba(args.word))
    exit()
    
workbook = openpyxl.load_workbook(filename)
list_words = set()

sheet = workbook.active
for row_num in range(2, 3000):
    word = sheet.cell(row_num, 4).value
    mean = sheet.cell(row_num, 1).value
    if(word == None):
        break
    if mean == None:
        print("正在处理第 %d 个单词: %s" % (row_num - 1, word))
        result = trans_by_ciba(word)
        time.sleep(1)
        if type(result) == dict :
            sheet.cell(row=row_num, column=1).value = result['mean']
            sheet.cell(row=row_num, column=3).value = result['proc']
            if word in list_words:
                print("==============>第 %d 个单词(%s)重复了" % (row_num, word))
            else:
                list_words.add(word)    
        elif type(result) == str:
            if "请求出错" in result:
                print("==============>第 %d 个单词(%s)请求出错" % (row_num - 1, word))
                workbook.save(filename)
            elif "未知错误" in result:
                print("==============>第 %d 个单词(%s)未知错误" % (row_num - 1, word))
                workbook.save(filename)
            
workbook.save(filename)